<template>
  <div class="bg-box relative">
    <div
      class=" w-[480px] register_box bg-[#fefefe] mr-[200px] flex flex-col items-center p-[10px] rounded-[5px] animate__animated animate__slideInLeft relative">
      <p class=" text-[30px] mb-[30px]">欢迎注册</p>
      <div class="flex flex-col">
        <div>
          <el-form label-width="50px" :model="userInfoData" :rules="userInfoDataRules" ref="registerFormEl">
            <el-scrollbar height="500px">
              <el-form-item prop="userName">
                <template #label>
                  <span class="iconfont icon-username text-[17px]"></span>
                </template>
                <el-input placeholder="请输入用户名" v-model="userInfoData.userName" />
              </el-form-item>
              <el-form-item prop="userPassword">
                <template #label>
                  <span class="iconfont icon-pwd text-[17px]"></span>
                </template>
                <el-input placeholder="请输入登录密码" type="password" v-model="userInfoData.userPassword" />
              </el-form-item>
              <el-form-item prop="nickname">
                <template #label>
                  <span class=" iconfont icon-nicheng text-[24px]"></span>
                </template>
                <el-input placeholder="请输入昵称" v-model="userInfoData.nickname" />
              </el-form-item>
              <el-form-item prop="introduce">
                <template #label>
                  <span class="iconfont icon-pingjia text-[19px]"></span>
                </template>
                <el-input v-model="userInfoData.introduce" :rows="2" type="textarea" placeholder="请填写自我评价" />
              </el-form-item>
              <el-form-item prop="phone">
                <template #label>
                  <span class="iconfont icon-shoujihao text-[22px]"></span>
                </template>
                <el-input placeholder="请输入手机号" type="number" v-model="userInfoData.phone" />
              </el-form-item>
              <el-form-item prop="email">
                <template #label>
                  <span class="iconfont icon-youxiang text-[20px]"></span>
                </template>
                <el-input placeholder="请输入邮箱" v-model="userInfoData.email" />
              </el-form-item>
              <el-form-item prop="code">
                <template #label>
                  <span class="iconfont icon-yanzhengma text-[20px]"></span>
                </template>
                <div class=" flex flex-row">
                  <el-input placeholder="请填写验证码" v-model="userInfoData.code" />
                  <el-button plain @click="sendCode" v-text="btnCode.btnText" :disabled="(btnCode.isDisabled
                  || !userInfoData.email)"></el-button>
                </div>
              </el-form-item>
              <el-form-item prop="area">
                <template #label>
                  <span class="iconfont icon-dizhi text-[20px]"></span>
                </template>
                <el-input placeholder="请输入地址" v-model="userInfoData.area" />
              </el-form-item>
              <el-form-item prop="sex">
                <template #label>
                  <span class="iconfont icon-xingbie text-[20px]"></span>
                </template>
                <el-radio-group v-model="userInfoData.sex">
                  <el-radio label="0">男</el-radio>
                  <el-radio label="1">女</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item prop="constellation">
                <template #label>
                  <span class=" iconfont icon-xingzuo text-[20px]"></span>
                </template>
                <el-select v-model="userInfoData.constellation" placeholder="请输入星座" class=" w-[220px]">
                  <el-option v-for="item in constellationList" :key="item" :value="item" />
                </el-select>
              </el-form-item>
              <el-form-item prop="birthday">
                <template #label>
                  <span class=" iconfont icon-shengri text-[20px]"></span>
                </template>
                <el-date-picker v-model="userInfoData.birthday" type="date" placeholder="请输入生日" size="default"
                  value-format="YYYY-MM-DD" class=" w-[220px]" />
              </el-form-item>
              <el-form-item prop="pic">
                <template #label>
                  <span class="iconfont icon-tupian text-[20px]"></span>
                </template>
                <el-upload drag multiple name="file" :action="baseURL + '/admin/file/upload'" :show-file-list="false"
                  :on-success="handkeUploadSuccess" :before-upload="beforeAvatarUpload">
                  <img v-if="userInfoData.pic" :src="userInfoData.pic"
                    class="object-contain w-full h-full object-center">
                  <template v-else>
                    <el-icon class="el-icon--upload">
                      <upload-filled />
                    </el-icon>
                    <div class="el-upload__text">
                      拖入图片 或 <em>点击选择图片上传</em>,不超过2M
                    </div>
                  </template>
                </el-upload>
              </el-form-item>
            </el-scrollbar>
          </el-form>
        </div>
        <div class="w-[410px] mt-16">
          <el-button type="primary" class=" w-full font-serif text-[17px]" :loading-icon="Loading"
            @click="submitRegisterForm" :loading="isLoading">注册</el-button>
        </div>
      </div>
      <p class=" mt-[20px] self-end text-[12px] text-[#ffff] hover:cursor-pointer hover:text-[#ffaf40] flex items-center"
        @click="$router.push({ name: 'Login' })">去登录<el-icon>
          <ArrowRight />
        </el-icon></p>
      <img src="../assets/svg/wave-register.svg" class=" absolute -z-10 bottom-0">
      <span class="iconfont icon-qingjing_chongwujiao absolute left-4 text-[32px] hover:cursor-pointer"
        @click="$router.replace({ name: 'Index' })"></span>
    </div>
  </div>
</template>

<script setup>
import { ArrowRight, UploadFilled, Loading } from "@element-plus/icons-vue";
import { ElNotification, ElMessage } from "element-plus";
import { result } from "lodash";
import { ref, reactive, onMounted, inject } from "vue";
import { useRouter } from "vue-router";
import API from "../utils/API";

const baseURL = inject("baseURL");
const isLoading = ref(false);
const router = useRouter();
const userInfoData = reactive({
  phone: "",
  email: "",
  sex: "",
  constellation: "",
  birthday: "",
  userName: "",
  userPassword: "",
  nickname: "",
  introduce: "",
  area: "",
  code: "",
  pic: ""

});
const constellationList = [
  "水瓶座", "双鱼座", "白羊座", "金牛座", "双子座", "巨蟹座", "狮子座", "处女座", "天枰座", "天蝎座", "射手座", "魔羯座"
]

/**
 * 发送验证码
 */
const btnCode = reactive({
  btnText: "发送验证码",
  isDisabled: false,
});
const sendCode = () => {
  btnCode.isDisabled = true;
  const btnTime = ref(60);
  const btnCodeId = setInterval(() => {
    btnTime.value--;
    // console.log(btnCode.btnTime);
    if (btnTime.value < 1) {
      clearInterval(btnCodeId);
      btnCode.isDisabled = false;
    }
    btnCode.btnText = btnTime.value == 0 ? "发送验证码" : btnTime.value + "s后重试";
  }, 1000)
  API.RegisterInfo.getVerificationCode(userInfoData).then(() => {
    ElMessage.success("发送成功");
  }).catch((error) => {
    ElNotification({
      title: "提示",
      message: "邮箱填写错误",
      type: "error"
    });
    clearInterval(btnCodeId);
    btnCode.isDisabled = false;
    console.log(error);
  })
}

/**
 * 表单验证规则
 */
const userInfoDataRules = {
  userName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  userPassword: [{ required: true, message: "请输入密码", trigger: "blur" }],
  nickname: [{ required: true, message: "请输入昵称", trigger: "blur" }],
  introduce: [{ required: true, message: "请填写自我评价", trigger: "blur" }],
  phone: [{ required: true, message: "请填写手机号", trigger: "blur" },
  {
    validator: async (rule, value, callback) => {
      if (value.length === 11 && /^1[3-9]\d{9}$/.test(value)) {
        callback()
      } else {
        callback(new Error("手机号格式不正确"));
      }
    }, trigger: "blur"
  }],
  email: [{ required: true, message: "请输入邮箱", trigger: "blur" },
  {
    validator: async (rule, value, callback) => {
      const reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
      if (reg.test(value)) {
        callback()
      } else {
        callback(new Error("邮箱格式不正确"));
      }
    }, trigger: "blur"
  }],
  code: [{ required: true, message: "请填写验证码", trigger: "blur" }],
  area: [{ required: true, message: "请输入地址", trigger: "blur" }],
  sex: [{ required: true, message: "请选择性别", trigger: "blur" }],
  constellation: [{ required: true, message: "请选择星座", trigger: "blur" }],
  birthday: [{ required: true, message: "请选择生日日期", trigger: "blur" }],
  pic: [{ required: true, message: "请上传头像", trigger: "blur" }],
}

const registerFormEl = ref(null);
const submitRegisterForm = () => {
  registerFormEl.value.validate(valid => {
    if (valid) {
      console.log("验证成功");
      checkRegister();
    }
    else {
      console.log("验证失败");
      ElMessage.error("请填写内容");
    }
  });
}

const checkRegister = () => {
  isLoading.value = true;
  API.RegisterInfo.checkRegister(userInfoData).then(() => {
    ElNotification({
      title: "系统提示",
      message: "注册成功",
      type: "success",
      position: "top-left"
    });
    router.replace({ name: "Login" })
  }).catch(error => {
    // console.log(error);
  }).finally(() => {
    isLoading.value = false
  })
}


/**
 * 头像上传的方法
 * @param rawFile
 * @returns {boolean}
 */
const beforeAvatarUpload = (rawFile) => {
  let reg = /^image\/(jpe?g|gif|png|bmp|webp)$/;
  if (!reg.test(rawFile.type)) {
    ElMessage.error('请选择图片文件')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

/**
 * 上传图片成功以后的回调
 * @param response
 */
const handkeUploadSuccess = (response) => {
  userInfoData.pic = response.data;
  // console.log(response.data);
}


</script>

<style scoped lang="scss">
.bg-box {
  background-image: url(../assets/img/register-bg.png);
  width: 100vw;
  height: 100vh;
  background-size: cover;
  @apply flex justify-end items-center;

  .register_box {
    box-shadow: 3px 3px 4px 4px rgb(230, 227, 227);

    :deep(.el-scrollbar__view) {
      padding-right: 20px;
    }
  }
}
</style>